<template>
  <div class="email-material-container">
    <!-- 页面标题区域 -->

    <!-- 主要内容区域 -->
    <el-row :gutter="20">
      <!-- 左侧：素材分组树 -->
      <el-col :xs="24" :sm="24" :md="6" :lg="6" class="group-tree-col">
        <el-card shadow="hover" class="group-tree-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-folder-opened"></i>
              <span>素材分组</span>
            </div>
            <div class="header-actions">
              <el-button type="text" class="add-group-btn" @click="handleAddGroup">
                <i class="el-icon-plus"></i> 新建分组
              </el-button>
            </div>
          </div>

          <el-tree :data="groupTreeData" :props="defaultProps" :expand-on-click-node="false"
                   ref="tree" node-key="id" default-expand-all highlight-current
                   @node-click="handleNodeClick">
            <span class="custom-tree-node" slot-scope="{node,data}">
              <span class="node-label">
                <i v-if="data.id == 0" class="el-icon-s-home tree-icon" />
                <i v-else class="el-icon-document tree-icon" />
                {{ data.groupName }}
              </span>
              <span class="node-actions">
                <i class="el-icon-plus action-icon" title="增加" @click.stop="handleAddGroup(data)" v-if="data.id == 0"></i>
                <i class="el-icon-edit action-icon" title="编辑" @click.stop="handleGroupUpdate(data)" v-if="data.id != 0"></i>
                <i class="el-icon-delete action-icon" title="删除" @click.stop="handleGroupDelete(node, data)" v-if="data.id != 0"></i>
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧：素材列表 -->
      <el-col :xs="24" :sm="24" :md="18" :lg="18" class="material-list-col">
        <el-card shadow="hover" class="material-list-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-picture"></i>
              <span>{{ currentGroupName }}</span>
            </div>
<!--            <div class="header-actions">-->
<!--               <el-button-->
<!--                type="primary"-->
<!--                plain-->
<!--                icon="el-icon-plus"-->
<!--                size="small"-->
<!--                @click="handleAdd"-->
<!--              >新增</el-button>-->
<!--              <el-button-->
<!--                type="success"-->
<!--                plain-->
<!--                icon="el-icon-edit"-->
<!--                size="small"-->
<!--                :disabled="single"-->
<!--                @click="handleUpdate"-->
<!--              >修改</el-button>-->
<!--              <el-button-->
<!--                type="danger"-->
<!--                plain-->
<!--                icon="el-icon-delete"-->
<!--                size="small"-->
<!--                :disabled="multiple"-->
<!--                @click="handleDelete"-->
<!--              >删除</el-button>-->
<!--            </div>-->
          </div>

          <!-- 搜索和筛选工具栏 -->
          <div class="search-toolbar">
             <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
                <el-form-item>
        <el-radio-group v-model="queryParams.materialType" @change="handleQuery">
                    <el-radio-button label="">全部</el-radio-button>
                    <el-radio-button v-for="dict in dict.type.material_type" :key="dict.value" :label="dict.value">{{dict .label}}</el-radio-button>
        </el-radio-group>
      </el-form-item>
                <el-form-item prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入素材名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
                <el-form-item prop="createdId">
        <el-input
          v-model="queryParams.createdId"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
                  <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
          </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
          <!-- 素材表格 -->
          <div class="table-container">
            <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="素材名称" align="left" prop="materialName" width="180"/>
      <el-table-column label="素材图片" align="center" width="160" prop="materialPic">
        <template slot-scope="scope">
          <image-preview :src="scope.row.materialPic" :width="72" :height="128" />
        </template>
      </el-table-column>
      <el-table-column label="素材文案" align="left" prop="materialUrl" >
      </el-table-column>
      <el-table-column label="素材类型" align="center" prop="materialType"  width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_type" :value="scope.row.materialType"/>
        </template>
      </el-table-column>
      <el-table-column label="素材分组" align="center" prop="materialGroupName"  width="120">
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createdName"  width="100"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
          </div>

          <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
            class="pagination-container"
    />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改素材库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px"  append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="素材类型" prop="materialType">
          <el-radio-group v-model="form.materialType" @change="radioChange">
            <el-radio-button v-for="dict in dict.type.material_type" :key="dict.value" :label="dict.value" :disabled="dict.checked">{{dict.label}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="素材分组" prop="materialGroupId">
           <treeselect
             v-model="form.materialGroupId"
             :options="groupTreeSelect"
             :normalizer="normalizer"
             :show-count="true"
             placeholder="请选择素材分组"
             :searchable="false"
             :clearable="true"
           />
        </el-form-item>
        <el-form-item label="素材名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入素材名称" />
        </el-form-item>
        <el-form-item label="素材图片" prop="materialPic" v-if="picShow">
          <image-upload v-model="form.materialPic" :limit="1"/>
        </el-form-item>
        <el-form-item label="素材文案" prop="materialUrl"  v-if="charShow">
          <el-input v-model="form.materialUrl" type="textarea" :rows="8" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="素材附件" prop="materialFile"  v-if="fileShow">
          <FileUpload v-model="form.materialFileList"></FileUpload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 素材分组对话框 -->
    <el-dialog :title="groupDialogTitle" :visible.sync="groupDialogVisible" width="500px" append-to-body>
      <el-form ref="groupForm" :model="groupForm" :rules="groupRules" label-width="80px">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="groupForm.groupName" placeholder="请输入分组名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGroupForm">确 定</el-button>
        <el-button @click="cancelGroupForm">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listEmailmaterial,  getEmailmaterial,  updateEmailmaterial,  addEmailmaterial,  delEmailmaterial} from "@/api/email/emailmaterial";
import { listEmailmaterialgroup, getEmailmaterialgroup, delEmailmaterialgroup, addEmailmaterialgroup, updateEmailmaterialgroup } from "@/api/email/emailmaterialgroup";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "EmailMaterial",
  components: { Treeselect },
  dicts: ['material_type'],
  data() {
    return {
      picShow: false,
      charShow: true,
      fileShow: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 素材库表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: null,
        materialType: '', // Default to first tab
        createdId: null,
        materialGroupId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialType: [{ required: true, message: "素材类型不能为空", trigger: "blur" }],
        materialGroupId: [{ required: true, message: "素材分组不能为空", trigger: "change" }],
        materialName: [{ required: true, message: "素材名称不能为空", trigger: "blur" }],
      },
      // 分组相关
      groupTreeData: [],
      groupTreeSelect: [],
      defaultProps: {
        children: 'children',
        label: 'groupName',
      },
      currentGroupId: null,
      currentGroupName: '素材管理',
      groupDialogVisible: false,
      groupDialogTitle: '',
      groupForm: {},
      groupRules: {
        groupName: [ { required: true, message: "分组名称不能为空", trigger: "blur" } ],
      },
    };
  },
  created() {
    this.getGroupTree();
    this.getList();
  },
  methods: {
    /** 查询素材库列表 */
    getList() {
      this.loading = true;
      this.queryParams.materialGroupId = this.currentGroupId;
      listEmailmaterial(this.queryParams).then(response => {
        this.materialList = response.rows.map(item => ({...item, materialFileList: JSON.parse(item.materialFile || '[]')}));
        this.total = response.total;
        this.loading = false;
      });
    },
    getGroupTree() {
      listEmailmaterialgroup({}).then(response => {
        const groups = response.rows || [];
        console.log('原始分组数据:', groups);

        // 处理树形结构用于左侧树组件
        const treeData = this.handleTree(groups, "id", "parentId");
        const rootNode = { id: 0, groupName: '全部分组', children: treeData };
        this.groupTreeData = [rootNode];

        // 处理扁平结构用于下拉选择 - 直接使用原始数据格式
        this.groupTreeSelect = groups.map(item => ({
          id: item.id,
          label: item.groupName,
          value: item.id
        }));

        console.log('处理后的分组选择数据:', this.groupTreeSelect);
      }).catch(error => {
        console.error('获取分组失败:', error);
        this.groupTreeData = [{ id: 0, groupName: '全部分组', children: [] }];
        this.groupTreeSelect = [];
      });
    },
    handleNodeClick(data) {
      if (data.id === 0) {
        this.currentGroupId = null;
        this.currentGroupName = '素材管理';
      } else {
        this.currentGroupId = data.id;
        this.currentGroupName = data.groupName;
      }
      this.handleQuery();
    },
    handleAddGroup(data) {
      this.resetGroupForm();
      this.groupDialogVisible = true;
      this.groupDialogTitle = "添加素材分组";
    },
    handleGroupUpdate(row) {
      this.resetGroupForm();
      const groupId = row.id;
      getEmailmaterialgroup(groupId).then(response => {
        this.groupForm = response.data;
        this.groupDialogVisible = true;
        this.groupDialogTitle = "修改素材分组";
      });
    },
    submitGroupForm() {
       this.$refs["groupForm"].validate(valid => {
        if (valid) {
          if (this.groupForm.id != null) {
            updateEmailmaterialgroup(this.groupForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.groupDialogVisible = false;
              this.getGroupTree();
            });
          } else {
            addEmailmaterialgroup(this.groupForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.groupDialogVisible = false;
              this.getGroupTree();
            });
          }
        }
      });
    },
    handleGroupDelete(node, data) {
       this.$modal.confirm('是否确认删除分组名称为"' + data.groupName + '"的数据项？').then(function() {
        return delEmailmaterialgroup(data.id);
      }).then(() => {
        this.getGroupTree();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    cancelGroupForm() {
      this.groupDialogVisible = false;
      this.resetGroupForm();
    },
    resetGroupForm() {
      this.groupForm = {
        id: null,
        groupName: null,
      };
      this.resetForm("groupForm");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        materialName: null,
        materialPic: null,
        materialUrl: null,
        materialType: '1',
        materialContent: null,
        materialFileList:'',
        materialGroupId: null,
      };
      this.resetForm("form");
      this.radioChange('1');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.currentGroupId = null;
      this.currentGroupName = "素材管理";
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加素材";
      if(this.currentGroupId) {
          this.form.materialGroupId = this.currentGroupId;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEmailmaterial(id).then(response => {
        this.form = response.data;
        this.radioChange(this.form.materialType);
        this.open = true;
        this.title = "修改素材";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          if (this.form.id != null) {
            updateEmailmaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEmailmaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该素材？').then(function() {
        return delEmailmaterial(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    radioChange(val) {
      if (val == 1) { // 文本
        this.picShow=false;this.charShow=true;this.fileShow=false;
      } else if (val == 2) { // 图片
        this.picShow=true;this.charShow=false;this.fileShow=false;
      } else if (val == 3) { // 视频
        this.picShow=false;this.charShow=true;this.fileShow=true;
      } else if (val == 4) { // 图文
        this.picShow=true;this.charShow=true;this.fileShow=false;
      } else if (val == 5) { // 附件
        this.picShow=false;this.charShow=true;this.fileShow=true;
      }
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.label,
        value: node.value || node.id
      };
    }
  }
};
</script>

<style scoped>
.email-material-container {
  padding: 0px;
  background-color: #f8f9fa;
  height: calc(100vh - 80px);
  display: flex;
  flex-direction: column;
}

.email-material-container > .el-row {
  flex-grow: 1;
  display: flex;
  margin: 0 !important;
}

.email-material-container > .el-row > .el-col {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 !important;
}

.email-material-container .el-card {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  margin: 0;
  border-radius: 0;
}

.email-material-container .el-card >>> .el-card__body {
  flex-grow: 1;
  overflow: hidden;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-title i {
  font-size: 18px;
  color: #409eff;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.group-tree-card .el-tree {
  background-color: transparent;
}

.group-tree-card .el-tree-node {
  margin-bottom: 4px;
}

.group-tree-card >>> .el-tree-node__content {
  height: 36px !important;
  line-height: 36px !important;
  min-height: 36px !important;
  padding: 0 10px 0 0 !important;
}

.group-tree-card .el-tree-node__expand-icon {
  padding: 6px;
}

.group-tree-card .el-tree-node__label {
  font-size: 14px;
}

.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 0px;
  font-size: 14px;
  height: 36px;
  line-height: 36px;
}

.node-label {
  display: flex;
  align-items: center;
}

.tree-icon {
  margin-right: 8px;
  font-size: 16px;
}

.node-actions {
  display: none;
  gap: 4px;
}

.custom-tree-node:hover .node-actions {
  display: flex;
}

.search-toolbar {
  margin-bottom: 16px;
  flex-shrink: 0;
}

.table-container {
  flex-grow: 1;
  overflow-y: auto;
  margin-bottom: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  max-height: calc(100vh - 360px);
  min-height: 300px;
}

.el-table {
  margin-bottom: 0;
}

.pagination-container {
  text-align: right;
  margin-top: 0;
  padding: 0px 0;
  flex-shrink: 0;
  border-top: 1px solid #ebeef5;
  background-color: #fff;
}

.add-group-btn {
  color: #3b82f6;
  font-size: 13px;
  padding: 6px 12px;
  border-radius: 6px;
  border: 1px solid #dbeafe;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  transition: all 0.3s ease;
  font-weight: 500;
}

.add-group-btn:hover {
  color: #ffffff;
  background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
  border-color: #3b82f6;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.action-icon {
  font-size: 14px;
  color: #9ca3af;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
  background: transparent;
}

.action-icon:hover {
  color: #ffffff;
  background: #3b82f6;
}

.group-tree-col {
  width: 300px !important;
  min-width: 300px;
  max-width: 300px;
  flex: 0 0 300px;
  padding-right: 0 !important;
}

.group-tree-card {
  width: 100%;
  margin-right: 0;
  border-right: 1px solid #ebeef5;
  border-radius: 0;
}

.material-list-col {
  flex: 1 !important;
  width: calc(100% - 300px) !important;
  max-width: none !important;
  padding-left: 0 !important;
}

.material-list-card {
  width: 100%;
  border-radius: 0;
  border-left: none;
}
</style>

